package com.sea.demo.shiro.controller;

import com.sea.demo.shiro.domain.User;
import com.sea.demo.shiro.form.UserForm;
import com.sea.demo.shiro.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @Author: 快乐在角落里
 * @Create: 2020/11/8 6:10
 * 用户相关接口
 */
@RestController
@RequestMapping("user")
public class UserController {

    private final Logger LOGGER = LogManager.getLogger(UserController.class);

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(method = RequestMethod.POST)
    public String insert(@RequestBody UserForm userForm){
        User user = new User();
        BeanUtils.copyProperties(userForm,user);
        userService.insert(user);
        LOGGER.info("USER ADDED SUCCESSFULLY ------ {}",user.toString());
        return "用户添加成功!";
    }

    @RequestMapping(method = RequestMethod.DELETE,path = "/{userId}")
    public String delete(@PathVariable("userId") Integer userId){
        if(whetherTheUserDoesNotExist(userId)){
            return "删除的用户不存在!";
        }
        if(whetherTheUserIsTheCurrentUser(userId)){
            return "不能删除当前用户!";
        }
        userService.delete(userId);
        return "删除成功!";
    }

    @RequestMapping(method = RequestMethod.PATCH)
    public String update(@RequestBody UserForm userForm){
        if(whetherTheUserDoesNotExist(userForm.getId())){
            return "修改的用户不存在!";
        }
        if(whetherTheUserIsTheCurrentUser(userForm.getId())){
            return "不能修改当前用户!";
        }
        User modifiedUser = new User();
        BeanUtils.copyProperties(userForm,modifiedUser);
        userService.update(modifiedUser);
        LOGGER.info("USER MODIFIED SUCCESSFULLY ------ {}","");
        return "用户修改成功!";
    }

    @RequestMapping(method = RequestMethod.GET)
    public List<User> queryUsersByUserName(@ModelAttribute("query") UserForm userForm){
        User user = new User();
        BeanUtils.copyProperties(userForm,user);
        return userService.select(user, userForm.getCurrentPage(), userForm.getPageSize());
    }


    private boolean whetherTheUserDoesNotExist(Integer userId){
        User modifiedUser = userService.selectOne(userId);
        return Objects.isNull(modifiedUser);
    }

    private boolean whetherTheUserIsTheCurrentUser(Integer userId){
        User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
        return userId.equals(currentUser.getId());
    }
}
